from django.conf import settings
from django.core.files.uploadedfile import InMemoryUploadedFile
from fdfs_client.client import Fdfs_client
from rest_framework import serializers, status
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from apps.goods.models import Brand
from apps.meiduo_admin.utils import CurPagination


class BrandSerializer(serializers.ModelSerializer):
    class Meta:
        model = Brand
        fields = ['id', 'name', 'logo', 'first_letter']

    def get_fdfs_cli(self):
        self.client = Fdfs_client(settings.FDFS_CONF)

    def create(self, validated_data):
        logo: InMemoryUploadedFile = validated_data.get('logo')
        self.get_fdfs_cli()
        upload_ret = self.client.upload_by_buffer(logo.read())
        if upload_ret['Status'] != 'Upload successed.':
            # 上传失败
            raise serializers.ValidationError('上传失败')
        print(upload_ret['Remote file_id'])
        validated_data['first_letter'] = validated_data['first_letter'].upper()
        validated_data['logo'] = upload_ret['Remote file_id']
        instance = Brand.objects.create(**validated_data)
        return instance

    def update(self, instance, validated_data):
        logo: InMemoryUploadedFile = validated_data.get('logo')
        self.get_fdfs_cli()
        upload_ret = self.client.upload_by_buffer(logo.read())
        if upload_ret['Status'] != 'Upload successed.':
            # 上传失败
            raise serializers.ValidationError('修改失败')
        print(upload_ret['Remote file_id'])
        validated_data['first_letter'] = validated_data['first_letter'].upper()
        validated_data['logo'] = upload_ret['Remote file_id']
        Brand.objects.filter(id=instance.id).update(**validated_data)
        return instance


class BrandsView(ModelViewSet):
    permission_classes = [IsAdminUser]
    serializer_class = BrandSerializer
    queryset = Brand.objects.order_by('id').all()
    pagination_class = CurPagination

    def simple(self, request):
        simple_brands = Brand.objects.order_by('id').values('id', 'name')
        return Response(simple_brands)
